package javango.contrib.hibernate;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.google.inject.Inject;

import javango.api.MethodObjectParams;
import javango.http.HttpRequest;
import javango.http.HttpResponse;
import javango.middleware.Middleware;
import javango.core.servers.RequestProcessor;

public class HibernateMiddleware extends Middleware implements RequestProcessor.Listener, HttpRequest.Listener {

	private final static Log log = LogFactory.getLog(HibernateMiddleware.class);
	
	protected HibernateUtil hibernateUtil;
	
	@Inject
	public HibernateMiddleware(HibernateUtil hibernateUtil) {
		super();
		this.hibernateUtil = hibernateUtil;
	}


	@Override
	public HttpResponse processRequest(HttpRequest req) {
		try {
			hibernateUtil.beginTransaction();		
		} catch (DaoException e) {
			log.error(e,e);
		}
		return super.processRequest(req);
	}

	
	@Override
	public HttpResponse processMethodAndParams(HttpRequest req,	MethodObjectParams map) {
		req.addListener(this);
		return super.processMethodAndParams(req, map);
	}


	@Override
	public HttpResponse processResponse(HttpRequest req, HttpResponse response) {
		try {
			log.debug("Attempting commit"); 
			hibernateUtil.commitTransaction();
		} catch (DaoException e) {
			log.error(e,e);
		}
		return super.processResponse(req, response);
	}

	@Override
	public HttpResponse processException(HttpRequest request, Throwable t) {
		try {
			if (log.isDebugEnabled()) log.debug("Attempting rollback due to " + t);
			hibernateUtil.rollbackTransaction();		
		} catch (DaoException e) {
			log.error(e,e);
		}
		return super.processException(request, t);
	}

	public void stopRequestProcessor(RequestProcessor requestProcessor) {
		// TODO Can we somehow whutdown hibernate here to avoid the locking problems with Jetty?
	}


	public void closeRequest(HttpRequest request) {
		try {
			log.debug("Closing session");
			hibernateUtil.closeSession();
		} catch (DaoException e) {
			log.warn(e,e);
		}		
	}
}
